const moment = require('moment')
Parse.Cloud.define('payQlOrderSuccess', async (req, res) => {
  const { orderNo, payTime, payMoney } = req.params
  if (!orderNo || !payTime || !payMoney) {
    return res.error('参数不正确')
  }

  try {
    const order = await new Parse.Query('QlOrder').equalTo('orderNo', orderNo).include('product').first()

    if (!order) {
      return res.error('无效订单')
    }

    if (order.get('status') !== 0) {
      return res.error('订单已经支付')
    }

    await order.save({status: 1, payMoney, payTime: new Date(payTime)})

    const vip = order.get('product')

    const monthes = vip.get('monthes')
    const account = await new Parse.Query('QlAccount').equalTo('user', order.get('user')).first()
    let endTime = account.get('endTime')
    endTime = (endTime && endTime.getTime()) || 0
    const currentTime = new Date().getTime()

    if (endTime > currentTime) {
      account.set('endTime', new Date(moment(endTime).add(monthes, 'M')))
    } else {
      account.set('endTime', new Date(moment().add(monthes, 'M')))
      account.set('startTime', new Date())
    }
    account.set('freeCount', 0)
    account.set('vip', vip)
    await account.save()
    res.success('ok')
  } catch (err) {
    console.log(err)
    res.error(err.message)
  }
})
